package com.unknowpupil.sell.controller;

import com.unknowpupil.sell.common.enums.ErrorCodeEnum;
import com.unknowpupil.sell.common.request.Result;
import com.unknowpupil.sell.exception.SellException;
import io.swagger.annotations.Api;
import jdk.nashorn.internal.runtime.regexp.joni.encoding.CharacterType;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;

/**
 * @Classname: WeChatController
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/12/31 15:28
 * @Description:
 * @Version: 1.0
 */
@Api(tags = {"支付认证获取openId"}, description = "支付认证获取openId")
@Controller
@RequestMapping(value = "/wechat")
@Slf4j
public class WeChatController {
    @Autowired
    private WxMpService wxMpService;
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        String url = "http://wx.dev.tmpan.cn/wechat/userInfo";
        String result = wxMpService.oauth2buildAuthorizationUrl("http://wx.dev.tmpan.cn/wechat/userInfo", WxConsts.OAuth2Scope.SNSAPI_USERINFO,"https://www.baidu.com");
        log.info("[微信网页授权] 获取code = {}" ,result);
        return  "redirect:"+result;
        //配置
        // 调用方法
    }
    @GetMapping("/userInfo")
    @ResponseBody
    public Result userInfo(@RequestParam("code") String code){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
             wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("[微信网页授权] {}",e);
            throw new SellException(ErrorCodeEnum.BUSINESS_FAIL);
        }
        log.info("[微信网页授权] 获取code = {}" ,code);
        String openId = wxMpOAuth2AccessToken.getOpenId();
        return  Result.ok(openId);

    }
}
